const utils = require("./utils")
const { writeFileSync } = require("fs")
//页面数量
let pageindex = 4
//页面地址
let pageallurl = []
//获取页面图片的href
let CurrentPageAllHref = []
let Currenindex = 0
let domain = "https://pic.netbian.com"
//页面加加
let index = 0;
let pageurl = "https://pic.netbian.com/4kmeinv/"
for (let index = 1; index < pageindex; index++) {
    pageallurl.push(index == 1 ? pageurl : `${pageurl}index_${index}.html`)
}
//获取当前页面全部 a 的href
getpagehref(pageallurl[index])
//https://pic.netbian.com/4kmeinv/index_2.html

// https://pic.netbian.com/4kmeinv/index_2.html
async function getpagehref(url) {
    let $ = await utils.get(url)
    $(".clearfix li a").each(function (i, v) { //each 循环
       
        CurrentPageAllHref.push(`${domain}${$(v).attr("href")}`)
    })
    getUrlInfo(CurrentPageAllHref[Currenindex])
}
//调取最后一页
async function getUrlInfo(url) {
    let $ = await utils.get(url)
    let urlx = $("#img img").attr("src")
    let name = urlx.substr(url.lastIndexOf("/") + 1) //substr 从什么开始截 lastIndexOf("/")获取下标

    downImg(name, `${domain}${urlx}`)
}

//调取图片
async function downImg(name, urlx) {
    console.log(urlx)
    let imgBuffer = await utils.get(urlx, "img");
    writeFileSync(`./img/${name}`, imgBuffer)//添加文件
    //添加一次 下标加一
    Currenindex += 1
    if (Currenindex < CurrentPageAllHref.length) {
        //调取最后一页
        getUrlInfo(CurrentPageAllHref[Currenindex])
    } else {
        //清空准备调取第二页
        Currenindex = 0
        CurrentPageAllHref = []
        index += 1
        if (index < pageindex) {
            //获取当前页面全部 a 的href
            getpagehref(pageallurl[index])
        }
    }
}